angular.module('starter.services', [])

  .factory('Shops', function ($q, $http) {
    var shops = [];
    return {
      all: function (schoolId) {
        var d = $q.defer();
        $http({
          url: 'http://115.159.212.133:8080/cloudorder/shop/getShops.do?schoolid=' + schoolId,
          method: 'get',
          headers: {
            'Content-Type': 'application/json'
          }
        }).success(function (response) {
          // alert(response[0].shopid);
          shops = response;
          d.resolve(response);
        }).error(function (error) {
          d.resolve(error);
          console.error("error " + error);
        });
        return d.promise;
      },

      get: function (shopId) {
        for (var i = 0; i < shops.length; i++){
          if (shops[i].shopid === parseInt(shopId)){
            return shops[i];
          }
        }
      },

      getShop: function (shopId) {
        var d = $q.defer();
        $http({
          url: 'http://115.159.212.133:8080/cloudorder/shop/getShop.do?shopid=' + shopId,
          method: 'get',
          headers: {
            'Content-Type': 'application/json'
          }
        }).success(function (response) {
          d.resolve(response);
        }).error(function (error) {
          d.resolve(error);
          console.error("error " + error);
        });
        return d.promise;
      }
    };
  })

  .factory('Foods', function ($q, $http) {
    var foods = [];
    return {
      getFoods: function (shopId) {
        var d = $q.defer();
        $http({
          url: 'http://115.159.212.133:8080/cloudorder/food/getFoods.do?shopid=' + shopId,
          method: 'get',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }).success(function (response) {
          foods = response;
          for (var i = 0; i < foods.length; i++) {
            foods[i].count = 0;
          }
          d.resolve(foods);
        }).error(function (error) {
          d.resolve(error);
          console.error("error " + error);
        });
        return d.promise;
      },
      getFood: function (foodId) {

      },
      getOrdersFood: function (foodList) {
        var orderFoods = [];
        for (var i = 0; i < foodList.length; i++) {
          for (var j = 0; j < foods.length; j++) {
            if (foodList[i].foodid === foods[j].foodid) {
              var f = {};
              f.name = foods[j].name;
              f.count = foodList[i].count;
              f.price = foods[j].price;
              orderFoods.push(f);
              break;
            }
          }
        }
        return orderFoods;
      }
    };
  })

  .factory('Orders', function ($q, $http) {
    var foodList = [];
    var order = {
      orderId: -1,
      shopId: -1,
      userId: -1,
      foods: foodList,
      totalPrice: 0,
      deliveryMethod: 1,
      note: "",
      stateCode: 0,
      orderTime: "",
      payMethod: 1
    };
    var localOrders=[];
    return {
      initOrder: function (shopId) {
        foodList = [];
        order.foods = foodList;
        order.shopId = shopId;
        order.totalPrice = 0;
      },
      //本地添加食品
      add: function (shop, food) {
        var tag = true;
        for (var i = 0; i < foodList.length; i++) {
          if (foodList[i].foodid === food.foodid) {
            foodList[i].count = foodList[i].count + 1;
            order.totalPrice = parseFloat(order.totalPrice) + parseFloat(food.price);
            tag = false;
            console.info("1==" + JSON.stringify(order));
          }
        }
        if (tag) {
          var f = {};
          f.foodid = food.foodid;
          f.count = 1;
          f.price = food.price;
          order.totalPrice = parseFloat(order.totalPrice) + parseFloat(food.price);
          foodList.push(f);
          console.info("2==" + JSON.stringify(order));
        }
        return order;
      },
      //本地删除或减少食品
      sub: function (shop, food) {
        for (var i = 0; i < foodList.length; i++) {
          if (foodList[i].foodid === food.foodid) {
            if (foodList[i].count > 1) {
              foodList[i].count--;
              order.totalPrice = parseFloat(order.totalPrice) - parseFloat(food.price);
            } else {
              foodList.splice(i, 1);
              order.totalPrice = parseFloat(order.totalPrice) - parseFloat(food.price);
            }
            console.info("3==" + JSON.stringify(order));
          }
        }
        return order;
      },
      //获得本地临时订单
      getTempOrder: function (){
        return order;
      },
      //获取缓存的订单
      get: function (orderId) {
        for (var i = 0; i < localOrders.length; i++){
          if (localOrders[i].orderid === parseInt(orderId)){
            return localOrders[i];
          }
        }
      },
      //联网获取订单列表
      getOrders: function (userId) {
        var d = $q.defer();
        $http({
          url: 'http://115.159.212.133:8080/cloudorder/OrderCtr/getOrders.do?userid=' + userId,
          method: 'get',
          headers: {
            'Content-Type': 'application/json'
          }
        }).success(function (orders) {
          localOrders = orders;
          d.resolve(orders);
        }).error(function (error) {
          d.resolve(error);
          console.error("error " + error);
        });
        return d.promise;
      },
      //联网获取订单
      getOrder: function (orderId) {
        var d = $q.defer();
        $http({
          url: 'http://115.159.212.133:8080/cloudorder/OrderCtr/getOrder.do?orderid=' + orderId,
          method: 'get',
          headers: {
            'Content-Type': 'application/json'
          }
        }).success(function (orders) {
          d.resolve(orders);
        }).error(function (error) {
          d.resolve(error);
          console.error("error " + error);
        });
        return d.promise;
      },
      getFinishedOrders:function (userId) {
        var d = $q.defer();
        $http({
          url: 'http://115.159.212.133:8080/cloudorder/OrderCtr/getHasFinishedOrders.do?userid=' + userId,
          method: 'get',
          headers: {
            'Content-Type': 'application/json'
          }
        }).success(function (orders) {
          d.resolve(orders);
        }).error(function (error) {
          d.resolve(error);
          console.error("error " + error);
        });
        return d.promise;
      }
    };
  })

  .factory('Addresses', function ($q, $http) {
    var addresses = [];
    var selectAddress;
    var address = {
      'deliveryaddressid': -1,
      'userid': -1,
      'name': '',
      'phonenub': '',
      'address': '',
      'isselect': false,
      'coordinateX': -1,
      'coordinateY': -1
    };
    return {
      getAddresses: function (userId) {
        var d = $q.defer();
        $http({
          url: 'http://115.159.212.133:8080/cloudorder/DeliveryAddress/getDeliveryAddresses.do?userid=' + userId,
          method: 'get',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }).success(function (addressList) {
          addresses = addressList;
          d.resolve(addresses);
        }).error(function (error) {
          d.resolve(error);
          console.error("error " + error);
        });
        return d.promise;
      },
      getAddress: function (addressId) {
        var d = $q.defer();
        $http({
          url: 'http://115.159.212.133:8080/cloudorder/DeliveryAddress/getDeliveryAddress.do?deliveryaddressid=' + addressId,
          method: 'get',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }).success(function (addr) {
          address = addr;
          d.resolve(address);
        }).error(function (error) {
          d.resolve(error);
          console.error("error " + error);
        });
        return d.promise;
      },
      delAddress: function (addressId) {
        var d = $q.defer();
        $http({
          url: 'http://115.159.212.133:8080/cloudorder/DeliveryAddress/deleteDeliveryAddress.do?deliveryaddressid=' + addressId,
          method: 'get',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }).success(function (result) {
          d.resolve(result);
        }).error(function (error) {
          d.resolve(error);
          console.error("error " + error);
        });
        return d.promise;
      },
      saveAddress: function (deliveryAddress) {
        var d = $q.defer();
        $http({
          url: 'http://115.159.212.133:8080/cloudorder/DeliveryAddress/putDeliveryAddress.do',
          method: 'post',
          headers: {
            'Content-Type': 'text/json;charset=utf-8'
          },
          data: deliveryAddress
        }).success(function (result) {
          d.resolve(result);
        }).error(function (error) {
          d.resolve(error);
          console.error("error " + error);
        });
        return d.promise;
      },
      updeteAddress: function (deliveryAddress) {
        var d = $q.defer();
        $http({
          url: 'http://115.159.212.133:8080/cloudorder/DeliveryAddress/updateDeliveryAddress.do',
          method: 'post',
          headers: {
            'Content-Type': 'text/json;charset=utf-8'
          },
          data: deliveryAddress
        }).success(function (result) {
          d.resolve(result);
        }).error(function (error) {
          d.resolve(error);
          console.error("error " + error);
        });
        return d.promise;
      },
      getSelectedAddress: function () {
        for (var i = 0; i < addresses.length; i++) {
          if (addresses[i].isSelect) {
            selectAddress = addresses[i];
            return selectAddress;
          }
        }
        return null;
      }
    }
  })

  .factory('Users', function () {
    var users = [{
      id: 0,
      name: 'Ben',
      face: 'img/ben.png',
      phone: '18686543365'
    }, {
      id: 1,
      name: 'Max',
      face: 'img/max.png',
      phone: '13003789494'
    }, {
      id: 2,
      name: 'Adam',
      face: 'img/adam.jpg',
      phone: '18686543365'
    }, {
      id: 3,
      name: 'Perry',
      face: 'img/perry.png',
      phone: '13003789494'
    }, {
      id: 4,
      name: 'Mike',
      face: 'img/mike.png',
      phone: '18686543365'
    }];
    return {
      get: function (userId) {
        for (var i = 0; i < users.length; i++) {
          if (users[i].id === parseInt(userId)) {
            users[i].phone = users[i].phone.substring(0, 3) + "****" + users[i].phone.substring(7, 11);
            return users[i];
          }
        }
        return null;
      },
      getRandom: function () {
        var index = parseInt(Math.random() * users.length);
        if (index >= users.length)
          return null;
        else {
          users[index].phone = users[index].phone.substring(0, 3) + "****" + users[index].phone.substring(7, 11);
          return users[index];
        }
      }
    };

  })

  .factory('Persons', function () {
    var persons = [{
      id: 0,
      name: '吧拉拉',
      phone: "111111110000",
      address: "四公寓A618",
      isSelect: true
    },
      {
        id: 1,
        name: '吧拉qqq拉',
        phone: "111133110000",
        address: "综合楼B区",
        isSelect: false
      },
      {
        id: 2,
        name: '吧拉qw拉',
        phone: "1111145510000",
        address: "综合楼D区",
        isSelect: false
      }];

    return {
      all: function () {
        return persons;
      },
      get: function (personId) {
        for (var i = 0; i < persons.length; i++) {
          if (persons[i].id === parseInt(personId)) {
            return persons[i];
          }
        }
        return null;
      },
      getSelected: function () {
        for (var i = 0; i < persons.length; i++) {
          if (persons[i].isSelect) {
            return persons[i];
          }
        }
      },
      add: function (name, phone) {
        var person = {
          id: persons.length,
          name: name,
          phone: phone,
          isSelect: false
        };
        persons.push(person);
        return persons;
      },
      remove: function (personId) {
        persons.splice(persons.indexOf(personId), 1);
      }
    };
  });
